#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql
import os
import traceback
import sys

print("========== 开始执行清空供应商表脚本 ==========")

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'passwd': '123456',
    'db': 'premade_food_trace',
    'charset': 'utf8mb4',
}

print(f"数据库配置信息: {db_config}")

def clear_suppliers():
    try:
        # 连接数据库
        print("连接数据库...")
        conn = pymysql.connect(
            host=db_config['host'],
            user=db_config['user'],
            passwd=db_config['passwd'],
            db=db_config['db'],
            charset=db_config['charset'],
            cursorclass=pymysql.cursors.DictCursor
        )
        cursor = conn.cursor()
        
        # 获取当前记录数
        cursor.execute("SELECT COUNT(*) as count FROM suppliers")
        count = cursor.fetchone()['count']
        print(f"当前供应商表有 {count} 条记录")
        
        # 执行清空操作
        print("清空供应商表...")
        cursor.execute("TRUNCATE TABLE suppliers")
        
        # 重置自增ID
        print("重置自增ID...")
        cursor.execute("ALTER TABLE suppliers AUTO_INCREMENT = 1")
        
        # 提交事务
        conn.commit()
        print("数据库操作已提交")
        
        # 验证结果
        cursor.execute("SELECT COUNT(*) as count FROM suppliers")
        new_count = cursor.fetchone()['count']
        print(f"操作后供应商表有 {new_count} 条记录")
        
        print("供应商表已清空，自增ID已重置")
        
    except Exception as e:
        print(f"清空供应商表出错: {str(e)}")
        print("详细错误信息:")
        traceback.print_exc()
    finally:
        # 关闭连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()
        print("数据库连接已关闭")

if __name__ == "__main__":
    try:
        # 执行清空操作
        print("开始执行清空操作...")
        clear_suppliers()
        print("清空操作执行完成")
    except Exception as e:
        print(f"主程序异常: {str(e)}")
        traceback.print_exc()
    
    print("========== 脚本执行结束 ==========")
    # 确保输出在终端显示
    sys.stdout.flush() 